//
//  RegistViewController.m
//  登陆注册
//
//  Created by 吴俊杰 on 2016/11/14.
//  Copyright © 2016年 吴俊杰. All rights reserved.
//

#import "JPRegistViewController.h"
#import "JPLoginViewController.h"
#import <SVProgressHUD.h>

@interface JPRegistViewController ()

// 手机号码
@property (weak, nonatomic) UITextField *phoneTextField;
// 验证码
@property (weak, nonatomic) UITextField *CAPTCHATextField;
// 密码
@property (weak, nonatomic) UITextField *secretTextField;
// 是否同意协议
@property (assign, nonatomic, getter = isAgreeProtocol) BOOL agreeProtocol;
// 发送验证码按钮
@property (strong, nonatomic) UIButton *sendCAPTCHABtn;
// 发送验证码倒计时
@property (assign, nonatomic) NSInteger time;

@end

@implementation JPRegistViewController {
    // 定时器
    NSTimer *_countDownTimer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupSubviews];
}

#pragma mark - 初始化界面
- (void)setupSubviews {
    
    //手机号码TextField
    UITextField *phoneTextField = [[UITextField alloc] init];
    [self.view addSubview:phoneTextField];
    self.phoneTextField = phoneTextField;
    
    phoneTextField.placeholder = @"请输入您的手机号码";
    phoneTextField.font = [UIFont systemFontOfSize:14.0];
    //设置边框模式
    phoneTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    CGFloat textFieldLR = 40;
    CGFloat textFieldTop = 200;
    CGFloat textFieldSpace = 20;
    [phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(textFieldLR);
        make.right.equalTo(self.view).offset(-textFieldLR);
        make.top.equalTo(self.view).offset(textFieldTop);
    }];
    
    //验证码TextField
    UITextField *CAPTCHATextField = [[UITextField alloc] init];
    [self.view addSubview:CAPTCHATextField];
    self.CAPTCHATextField = CAPTCHATextField;
    
    CAPTCHATextField.placeholder = @"请输入您收到的验证码";
    CAPTCHATextField.font = [UIFont systemFontOfSize:14.0];
    //设置边框模式
    CAPTCHATextField.borderStyle = UITextBorderStyleRoundedRect;
    
    CGFloat CAPTCHATextFieldR = self.view.center.x - 20;
    [CAPTCHATextField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(textFieldLR);
        make.right.equalTo(self.view).offset(-CAPTCHATextFieldR);
        make.top.equalTo(phoneTextField.mas_bottom).offset(textFieldSpace);
    }];
    
    //发送验证码按钮
    UIButton *sendCAPTCHABtn = [[UIButton alloc] init];
    [self.view addSubview:sendCAPTCHABtn];
    
    [sendCAPTCHABtn setTitle:@"获取验证码" forState:UIControlStateNormal];
//    [sendCAPTCHABtn sizeToFit];
    self.sendCAPTCHABtn = sendCAPTCHABtn;
    sendCAPTCHABtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [sendCAPTCHABtn setBackgroundImage:[UIImage imageNamed:@"buttonBackground"] forState:UIControlStateNormal];
    
    CGFloat sendCAPTCHABtnWidth = 80;
    [sendCAPTCHABtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.bottom.equalTo(CAPTCHATextField);
        make.right.equalTo(phoneTextField);
        make.width.mas_equalTo(sendCAPTCHABtnWidth);
    }];
    
    [sendCAPTCHABtn addTarget:self action:@selector(sendCAPTCHABtnAction:) forControlEvents:UIControlEventTouchUpInside];

    //密码TextField
    UITextField *secretTextField = [[UITextField alloc] init];
    [self.view addSubview:secretTextField];
    self.secretTextField = secretTextField;
    // 隐藏密码
    self.secretTextField.secureTextEntry = NO;
    
    secretTextField.placeholder = @"请输入密码";
    secretTextField.font = [UIFont systemFontOfSize:14.0];
    //设置边框模式
    secretTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    [secretTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(textFieldLR);
        make.right.equalTo(self.view).offset(-textFieldLR);
        make.top.equalTo(CAPTCHATextField.mas_bottom).offset(textFieldSpace);
    }];
    
    //协议勾选按钮
    UIButton *selectBtn = [[UIButton alloc] init];
    [self.view addSubview:selectBtn];
    [selectBtn setImage:[UIImage imageNamed:@"login_protocol"] forState:UIControlStateSelected];
    [selectBtn setImage:[UIImage imageNamed:@"login_unSelectProtocol"] forState:UIControlStateNormal];
    
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(secretTextField).offset(40);
        make.top.equalTo(secretTextField.mas_bottom).offset(40);
        make.width.height.mas_equalTo(18);
    }];
    
    [selectBtn addTarget:self action:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //协议label
    UILabel *protocolLabel = [[UILabel alloc] init];
    [self.view addSubview:protocolLabel];
    
    [protocolLabel setText:@"本人已同意并阅读"];
    protocolLabel.font = [UIFont systemFontOfSize:14.0];
    
    [protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(selectBtn.mas_right).offset(15);
        make.centerY.equalTo(selectBtn.mas_centerY);
    }];
    
    //查看协议button
    UIButton *protocolBtn = [[UIButton alloc] init];
    [self.view addSubview:protocolBtn];
    [protocolBtn setTitle:@"用户协议" forState:UIControlStateNormal];
    protocolBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [protocolBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [protocolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(protocolLabel.mas_right).offset(15);
        make.centerY.equalTo(protocolLabel.mas_centerY);
    }];
    
    //下一步button
    UIButton *nextBtn = [[UIButton alloc] init];
    [self.view addSubview:nextBtn];
    
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"buttonBackground"] forState:UIControlStateNormal];
    
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(phoneTextField);
        make.top.equalTo(protocolLabel.mas_bottom).offset(40);
    }];
    //添加点击事件
    [nextBtn addTarget:self action:@selector(nextBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 倒计时方法

/**
 开始倒计时
 */
- (void)timeFireMethod {
    
    self.time--;
    [self.sendCAPTCHABtn setTitle:[NSString stringWithFormat:@"%zds",self.time] forState:UIControlStateDisabled];
//    [self.sendCAPTCHABtn sizeToFit];
    self.sendCAPTCHABtn.enabled = NO;
    if (self.time == 0) {
        [_countDownTimer invalidate];
        self.sendCAPTCHABtn.enabled = YES;
        [self.sendCAPTCHABtn setTitle:@"重新发送" forState:UIControlStateNormal];
//        [self.sendCAPTCHABtn sizeToFit];
    }
}

#pragma mark - 按钮点击的方法
/**
 获取验证码
 */
- (void)sendCAPTCHABtnAction:(UIButton *)sender {
    // 设置弹窗显示时间
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    if (![self isPhoneNumWith:self.phoneTextField.text]) {
        // 弹窗提示
        [SVProgressHUD showErrorWithStatus:@"不合法的手机号!"];
        return;
    }
    //调用第三方框架的方法发送验证码
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phoneTextField.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
        if (!error) {
            self.sendCAPTCHABtn.enabled = NO;
            
            [SVProgressHUD showSuccessWithStatus:@"获取成功!"];
            // 创建定时器
            self.time = 10;
            _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
        } else {
            [SVProgressHUD showErrorWithStatus:@"获取失败!"];
        }
    }];
}

/**
 提交验证码
 */
- (void)nextBtnAction:(UIButton *)sender {
    
    NSString *searchText = self.secretTextField.text;
    
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    // 判断是否阅读并同意用户协议
    if (!self.isAgreeProtocol) {
        [SVProgressHUD showErrorWithStatus:@"请先阅读并同意用户协议!"];
        return;
    }
    // 判断密码是否大于6位数
    if (![self isSecretWith:searchText] || [self isAllNumberWith:searchText] || [self isAllLetterWith:searchText]) {
        [SVProgressHUD showErrorWithStatus:@"密码必须为6-16位数字以及字母的组合!"];
        return;
    }
    //调用第三方框架方法提交验证码
    [SMSSDK commitVerificationCode:self.CAPTCHATextField.text phoneNumber:self.phoneTextField.text zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
        [SVProgressHUD setMinimumDismissTimeInterval:1.0];
        if (!error) {
            //记住账号
            [[NSUserDefaults standardUserDefaults] setObject:self.phoneTextField.text forKey:@"phone"];
            //保存密码到钥匙串
            BOOL isSaved = [SSKeychain setPassword:self.secretTextField.text forService:[NSBundle mainBundle].bundleIdentifier account:self.phoneTextField.text];
            
            if (isSaved) {
                //跳转到登录界面
                JPLoginViewController *vc = [[JPLoginViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                [SVProgressHUD showSuccessWithStatus:@"注册成功!"];
            }
        }else {
            [SVProgressHUD showErrorWithStatus:@"验证失败!"];
        }
    }];
}

/**
 选中协议选择按钮
 */
- (void)selectBtnAction:(UIButton *)sender {
    
    sender.selected = !sender.isSelected;
    self.agreeProtocol = sender.isSelected;
}

#pragma mark - 正则表达式方法
/**
 判断是否符合手机号编码规范
 */
- (BOOL) isPhoneNumWith:(NSString *)searchText {
    
    NSString* number=@"^1[3|4|5|7|8][0-9]\\d{8}$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:searchText];
}

/**
 判断是否符合密码规范
 */
- (BOOL) isSecretWith:(NSString *)searchText {
    
    NSString* number=@"^[A-Za-z0-9]{6,16}$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:searchText];
}

/**
 判断是否全数字
 */
- (BOOL) isAllNumberWith:(NSString *)searchText {
    
    NSString* number=@"^[0-9]*$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:searchText];
}

/**
 判断是否全字母
 */
- (BOOL) isAllLetterWith:(NSString *)searchText {
    
    NSString* number=@"^[A-Za-z]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:searchText];
}

- (void)dealloc {
    _countDownTimer = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
